package com.arpa.oms.controller;


import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.oms.domain.dto.OmsDefaultWarehouseDTO;
import com.arpa.oms.domain.entity.OmsCustomer;
import com.arpa.oms.domain.entity.OmsDefaultWarehouse;
import com.arpa.oms.domain.vo.OmsCustomerVO;
import com.arpa.oms.domain.vo.OmsDefaultWarehouseVO;
import com.arpa.oms.service.IOmsDefaultWarehouseService;
import com.arpa.wms.domain.consts.NumConst;
import com.arpa.wms.domain.consts.PropertyConst;
import com.arpa.wms.domain.dto.WarehouseDTO;
import com.arpa.wms.domain.entity.Warehouse;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.WarehouseVO;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 默认发货仓库 前端控制器
 * </p>
 *
 * @author wangdong
 * @since 2021-07-27
 */
@Api(tags = "默认发货仓库")
@RestController
@RequestMapping(value = "/omsDefaultWarehouse", produces = "application/json;charset=UTF-8")
@Log4j2
public class OmsDefaultWarehouseController {

    @Autowired
    private IOmsDefaultWarehouseService iOmsDefaultWarehouseService;


    /**
     * 获取默认发货仓库列表
     *
     * @param warehouseDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 仓库 列表", notes = "获取 仓库 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")

    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = WarehouseVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(OmsDefaultWarehouseDTO warehouseDTO, HttpServletRequest request) {
        try {

            String shipmentCodes =UserUtil.getLoginWarehouseCodeOrShipmentCode();
            warehouseDTO.setShipmentCode(shipmentCodes);
            OmsDefaultWarehouseVO warehouseVOSum = iOmsDefaultWarehouseService.queryListSum(warehouseDTO);
            List<OmsDefaultWarehouseVO> warehouseVOList = iOmsDefaultWarehouseService.queryList(warehouseDTO);

            Page returnPage = new Page(warehouseDTO.getPageNum(), warehouseDTO.getPageSize());
            returnPage.setRecords(warehouseVOList);
            returnPage.setTotal(warehouseVOSum.getTotal());
            returnPage.setSumObject(warehouseVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    /**
     * 添加 仓库
     *
     * @param entity  Warehouse
     * @param request
     * @return
     */
    @ApiOperation(value = "添加仓库 ", notes = "添加仓库 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@RequestBody @Valid OmsDefaultWarehouseDTO entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            entity.setStatus(1);
            iOmsDefaultWarehouseService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改仓库
     *
     * @param entity  仓库
     * @param request
     * @return
     */
    @ApiOperation(value = "修改仓库", notes = "修改仓库")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@RequestBody @Validated(OmsDefaultWarehouse.Update.class)OmsDefaultWarehouse entity, HttpServletRequest request) {
        Result validResult;
        if (StrUtil.isBlank(entity.getCode())) {
            return Result.error("code不能为空");
        }

        // 校验“启用库位管理”，如果是刚关闭，则校验库存，并停用库区库位
        if(NumConst.NUM_ZERO.equals(entity.getLocationManagement())) {
            validResult = iOmsDefaultWarehouseService.closeLocationManagement(entity);
            if (!validResult.isOk()) {
                return validResult;
            }
        }

        int updateNum = iOmsDefaultWarehouseService.updateByCode(entity);
        if (updateNum == 0) {
            return Result.error("没有更新数据！code:" + entity.getCode());
        } else {
            return Result.ok("修改成功,更新" + updateNum + "条数据！");
        }
    }



    /**
     * 获取仓库详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取客户详情", notes = "获取客户详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "客户code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsCustomer.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result customer(@PathVariable String code, HttpServletRequest request) {
        try {
            OmsDefaultWarehouseVO entity = iOmsDefaultWarehouseService.getOneByCode(code);
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 仓库启用
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "仓库启用", notes = "仓库启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "仓库标识", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @PutMapping(value = "/active")
    public Result active(@RequestParam  List<String> codes,HttpServletRequest request) {
        int updateNum =  iOmsDefaultWarehouseService.activeStatus(codes);
        int failNum = codes.size() - updateNum;
        return Result.ok("启用成功" + updateNum + "条；失败" + failNum + "条；");
    }


    /**
     * 仓库停用
     *
     * @param codes 商品标识
     * @param request
     * @return
     */
    @ApiOperation(value = "仓库停用", notes = "仓库停用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "仓库标识", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @PutMapping(value = "/unactive")
    public Result unactive(@RequestParam List<String> codes,HttpServletRequest request) {

        Map<String,Object> result = iOmsDefaultWarehouseService.unactiveStatus(codes);
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        List<String> msg = MapUtil.get(result,"msg",List.class);
        int failNum = codes.size() - success;
        StringBuilder builder = new StringBuilder();
        builder.append("停用成功" + success + "条；失败" + failNum + "条；");
        if(IterUtil.isNotEmpty(msg)){
            for(String m: msg){
                builder.append("<br><font color='red'>仓库【"+m+"】停用失败;</font>");
            }
        }
        return Result.ok(builder.toString());
    }

}

